package com.ljy.utyun.swagger;

import java.io.File;
import java.util.List;

/**
 * @author lijunying
 * @date 2020/10/15 15:40
 */
public class ControllerSwaggerProcessor extends SwaggerProcessor{


    @Override
    public List<String> doProcess(File file,List<String> valueList){
//        加入import
        valueList.add(2,"import io.swagger.annotations.ApiOperation;");

//        加入注解
        for(int i=0;i<valueList.size();i++){
            String line=valueList.get(i);
            int tabIndex=-1;
            if((tabIndex=checkHasMappingAnnotation(line))==-1){
                continue;
            }
            //排除
            if(line.indexOf("public class")!=-1){
                continue;
            }

            String name=getChname(valueList,i);

            StringBuilder tabSb=new StringBuilder();
            for(int index=0;index<tabIndex;index++){
                tabSb.append("\t");
            }

            valueList.add(getAddLineIndex(valueList,i),tabSb.toString()+"@ApiOperation(\""+name+"\")");
            i++;
        }
        return valueList;
    }


    @Override
    public boolean checkCanProcess(File file) {
        return file.getName().lastIndexOf("Controller.java")!=-1;
    }

    private int checkHasMappingAnnotation(String line){
//        已经注释了
        if(line.trim().startsWith("//")){
            return -1;
        }

        String[] mappingAnnotationArr={"@PostMapping","@GetMapping"
//                ,"@RequestMapping"
        };
        int index=-1;
        for(String anno:mappingAnnotationArr){
            if((index=line.indexOf(anno))!=-1){
                break;
            }
        }
        return index;
    }

    private String getChname(List<String> valueList,int index){
        index--;
        while(valueList.get(index).indexOf("/**")==-1){
            //到了上一个方法的末端
            if(valueList.get(index).indexOf("}")!=-1){
                return "";
            }
            index--;
        }
        index++;
        String line=valueList.get(index);
        int start=line.indexOf("* ");
        if(start==-1){
            return "";
        }
        return line.substring(start+2);
    }
}
